<template>
  <div class="layout">
    <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" :rules="rules" label-width="150px" class="formstyle">
      <el-form-item label="菜品名称：" prop="name">
        <el-input v-model="ruleForm.name" style="width:300px" />
      </el-form-item>
      <el-form-item label="菜品分类：" prop="region">
        <el-select v-model="ruleForm.categoryId" placeholder="请选择菜品分类">
          <el-option v-for="(item,index) in region" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="菜品价格：" style="width:800px">
        <el-input v-model="ruleForm.price" style="width:200px" />
      </el-form-item>
      <el-form-item label="口味做法配置：">
        <div v-for="(item,index) in dynamicTags" :key="item.id" class="configuration">
          <el-input v-model="item.name" style="width:100px" />
          <div>
            <el-tag
              v-for="tag in JSON.parse(item.value)"
              :key="tag"
              closable
              @close="handleClose(tag,item.id)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              ref="saveTagInput"
              v-model="inputValue[index]"
              style="width:70px"
              class="input-new-tag inputxi"
              size="small"
              @keyup.enter.native="handleInputConfirm(index)"
              @click="showInput(index)"
            />
          </div>
          <el-link type="danger" @click="Delete(index)">删除</el-link>
        </div>
        <el-button type="warning" @click="Addlist">添加口味</el-button>
      </el-form-item>
      <el-form-item label="菜品描述：" style="width:90%">
        <el-input v-model="ruleForm.description" type="textarea" />
      </el-form-item>
      <el-form-item label="菜品图片：" style="width:90%">
        <el-upload
          class="avatar-uploader"
          action="/"
          :http-request="uploadImage"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-image v-if="ruleForm.image" :src="getUrl(ruleForm.image)" style="width:200px;height:200px" />
          <i v-else class="el-icon-plus avatar-uploader-icon" />

        </el-upload>
      </el-form-item>
      <el-form-item style="width:800px">
        <el-button @click="resetForm('ruleForm')">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { queryDishById, getCategoryList, editDish, uploadImage } from '@/api/food'
export default {
  data() {
    return {
      ruleForm: {
        image: ''
      },
      loading: false,
      inputValue: ['', '', ''],
      inputVisible: true,
      tags: [],
      rules: {
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ]
      },
      region: [],
      dynamicTags: [{ name: '', value: '[]' }],
      imageUrl: ''
    }
  },
  created() {
    this.loading = true
    this.$route.meta.title = this.$route.query.title
  },
  async mounted() {
    this.region = await getCategoryList({ type: 1 })
    if (this.$route.query.id) {
      this.ruleForm = await queryDishById(this.$route.query.id)
      this.dynamicTags = this.ruleForm.flavors
    }
    this.loading = false
  },
  methods: {
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.ruleForm.image = this.imageUrl
      console.log(res, file, this.imageUrl)
    },
    // 图片限制
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      return isJPG
    },
    getUrl(image) {
      return `${process.env.VUE_APP_BASE_API}/common/download?name=${image}`
    },
    setUrl() {
      return `${process.env.VUE_APP_BASE_API}/common/download`
    },
    // 保存
    async submitForm() {
      try {
        await editDish(this.ruleForm)
        this.$message.success('修改成功')
        this.$router.go(-1)
      } catch {
        console.log('error submit!!')
      }
    },
    // 取消
    resetForm() {
      this.ruleForm = {}
      this.$router.go(-1)
    },
    // 删除单个标签
    handleClose(tag, ID) {
      this.dynamicTags.map((item) => {
        if (
          item.id === ID) {
          const xixi = JSON.parse(item.value)
          xixi.splice(JSON.parse(item.value).indexOf(tag), 1)
          item.value = JSON.stringify(xixi)
          return item
        }
      })
    },
    // 删除单行
    Delete(index) {
      this.dynamicTags.splice(index, 1)
    },
    // 添加单个标签
    handleInputConfirm(index) {
      const xixi = JSON.parse(this.dynamicTags[index].value)
      xixi.push(this.inputValue[index])
      this.dynamicTags[index].value = JSON.stringify(xixi)
      this.inputValue[index] = ''
    },
    // 添加单行
    Addlist() {
      this.dynamicTags.push({ name: '', value: '[]' })
    },
    uploadImage(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      uploadImage(formData).then(res => {
        this.ruleForm.image = res
        console.log(this.ruleForm.image)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.layout{
    padding: 30px;
    background: #f3f4f7;
    .formstyle{
        background: #ffffff;
        padding: 30px 100px;
        display: flex;
        flex-wrap: wrap;
    }
}
.configuration{
    display: flex;
}
.inputxi{
    width: 70px;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
